/*
 * Copyright (c) 2017-present, CV4J Contributors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.cv4j.core.spatial.conv;

import com.cv4j.core.datamodel.ColorProcessor;
import com.cv4j.core.datamodel.ImageProcessor;
import com.cv4j.core.filters.GaussianBlurFilter;
import com.cv4j.image.util.Tools;

import java.util.Optional;

/**
 * usmfilter
 *
 * @author dev
 * @date 2021/07/22
 */
public class USMFilter extends GaussianBlurFilter {
    private double weight;

    /**
     * usmfilter
     */
    public USMFilter() {
        this.weight = 0.6;
    }

    /**
     * 获得重量
     *
     * @return double
     */
    public double getWeight() {
        return weight;
    }

    /**
     * 设置权重
     *
     * @param weight 重量
     */
    public void setWeight(double weight) {
        this.weight = weight;
    }

    /**
     * 做的过滤器
     *
     * @param src src
     * @return {@link Optional<ImageProcessor>}
     */
    @Override
    public Optional<ImageProcessor> doFilter(ImageProcessor src) {
        int total = width * height;
        byte[] rgb = new byte[total];
        byte[] green = new byte[total];
        byte[] blue = new byte[total];
        System.arraycopy(RED, 0, rgb, 0, total);
        System.arraycopy(GREED, 0, green, 0, total);
        System.arraycopy(this.BLUE, 0, blue, 0, total);
        byte[][] output = new byte[3][total];

        // 高斯模糊
        super.doFilter(src);

        int rs = 0;
        int gs = 0;
        int bs = 0;

        int r1 = 0;
        int g1 = 0;
        int b1 = 0;

        int r2 = 0;
        int g2 = 0;
        int b2 = 0;

        for (int i = 0; i < total; i++) {
            r1 = rgb[i] & 0xff;
            g1 = green[i] & 0xff;
            b1 = blue[i] & 0xff;

            r2 = RED[i] & 0xff;
            g2 = GREED[i] & 0xff;
            b2 = this.BLUE[i] & 0xff;

            rs = (int) ((r1 - weight * r2) / (1 - weight));
            gs = (int) ((g1 - weight * g2) / (1 - weight));
            bs = (int) ((b1 - weight * b2) / (1 - weight));

            output[0][i] = (byte) Tools.clamp(rs);
            output[1][i] = (byte) Tools.clamp(gs);
            output[2][i] = (byte) Tools.clamp(bs);
        }

        ((ColorProcessor) src).putRGB(output[0], output[1], output[2]);
        output = null;
        return Optional.ofNullable(src);
    }
}
